package com.rcadmin.core.web;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.gson.JsonObject;
import com.rcadmin.util.JsonUtils;

/**
 * Jsonp的一个辅助请求类
 * 
 * @author Joeson Chan<chenxuegui1234@163.com>
 * @since 2016年3月21日
 */
public class AjaxJsonpUtils {

	protected static Logger logger = LoggerFactory
			.getLogger(AjaxJsonpUtils.class);

	/**
	 * 是否是jsonpa请求
	 * 
	 * @param request
	 * @return
	 */
	public static boolean isJsonpRequest(HttpServletRequest request) {
		if (null == request) {
			logger.error("request can not be null");
			return false;
		}

		if (!StringUtils.isEmpty(request.getParameter("callbackparam")))
			return true;
		return false;
	}

	/**
	 * jsonp 响应返回json数据
	 * 
	 * @param request
	 *            当前请求
	 * @param response
	 *            当前响应
	 * @param json
	 *            响应json数据
	 * @throws IOException
	 */
	public static void outJson(HttpServletRequest request,
			HttpServletResponse response, String json) throws IOException {
		response.setContentType("text/json");
		String callbackparam = request.getParameter("callbackparam");

		JsonObject jsonObject = JsonUtils.parse(json);
		String jsonpResut = "ajax.jsonpCallback(" + jsonObject.toString()
				+ ",'" + callbackparam + "')";
		//logger.info(jsonpResut);
		response.getWriter().write(jsonpResut);
	}

}
